﻿using Gnivc.CarDealership.Api.Application.Commands.Vehicles.CreateVehicle;
using Gnivc.CarDealership.Api.Application.Queries.Vehicles.GetAvailableVehicles;
using Gnivc.CarDealership.Api.Contracts.Vehicles.CreateVehicle;
using Gnivc.CarDealership.Api.Contracts.Vehicles.GetAvailableVehicles;
using Mapster;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace Gnivc.CarDealership.Api.Controllers;

[Route("api/[controller]")]
public class VehiclesController : ApiController
{
    public VehiclesController(IMediator mediator) 
        : base(mediator) { }

    [HttpGet("all")]
    public async Task<IResult> GetVehicles(
        [FromQuery] GetAvailableVehiclesRequest request)
    {
        var query = new GetAvailableVehiclesQuery(
            request.SelectedDate,
            request.BrandId,
            request.ModelId);

        var result = await Mediator.Send(query);

        if (result.IsError)
            return Problem(result.Errors);

        var response = 
            new GetAvailableVehiclesResponse(result.Value.Vehicles);

        return Results.Ok(response);
    }

    [HttpPost("create")]
    public async Task<IResult> CreateVehicle([FromBody] CreateVehicleRequest request)
    {
        var command = request.Adapt<CreateVehicleCommand>();

        var result = await Mediator.Send(command);

        if (result.IsError)
            return Problem(result.Errors);

        var response = result.Value.Adapt<CreateVehicleResponse>();

        return Results.Ok(response);
    }
}